﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Support;
using Microsoft.Office.Server.UserProfiles;
using MS.InformationManagement.Core.Actions;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.BLL.Helper;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.Support;
using MS.InformationManagement.DAL.DTOs;

namespace MS.InformationManagement.BLL.RequestBoVo
{
    public class RequestVoBo
    {
        //public List<UserDTO> GetUsers()
        //{
        //    List<UserDTO> users = new List<UserDTO>();
            
        //    string userSectionName = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);
        //    Seccion userSection = GetUserSection(userSectionName);
        //    List<Seccion> parentSections = RecursiveHelper.GetParentSections(userSection, true);

        //    SPUserCollection siteUsers = SPContext.Current.Web.Users;
            
        //    foreach (Seccion currentSection in parentSections) {                
        //        SPUser currentUser = (from SPUser user in siteUsers
        //                              where user.Name.Equals(currentSection.UsuarioEncargadoCorrespondencia)
        //                             select user).SingleOrDefault();
        //        users.Add(new UserDTO{LoginName = currentUser.LoginName.GetUserWithOutDomain(),DisplayName =string.Format("{0} - {1}", currentSection.Title, currentUser.Name) });                    
        //    }

        //    return users;
        //}

        public List<UserDTO> GetUsers()
        {
            string userSectionName = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);
            List<UserDTO> users = RecursiveHelper.IsUserSectionAdmin(SPContext.Current.Web.CurrentUser.Name)
                ? GetUsersForAdminUser(userSectionName)
                : GetUsersForStandardUser(userSectionName);
            return users;
        }

        private List<UserDTO> GetUsersForAdminUser(string sectionName)
        {
            Seccion currentSection = GetUserSection(sectionName);
            Dictionary<string, string> result = PeopleHelper.GetUsersByProperty(GlobalConstants.UP_DEPARTMENT, sectionName, false);
            List<UserDTO> users = (from user in result select new UserDTO { LoginName = user.Key, DisplayName = user.Value }).ToList();
            RecursiveHelper.PurgeUsers(ref users, GlobalConstants.ROLE_VB);
            RecursiveHelper.AddSectionAdminUsers(ref users, false);
            return users;
        }

        private List<UserDTO> GetUsersForStandardUser(string sectionName)
        {
            Seccion currentSection = GetUserSection(sectionName);
            Dictionary<string, string> result = PeopleHelper.GetUsersByProperty(GlobalConstants.UP_DEPARTMENT, sectionName, false);
            List<UserDTO> users = (from user in result select new UserDTO { LoginName = user.Key, DisplayName = user.Value }).ToList();
            RecursiveHelper.PurgeUsers(ref users, GlobalConstants.ROLE_VB);
            string sectionOwnerName = currentSection.UsuarioEncargadoCorrespondencia;
            RecursiveHelper.AddSectionOwner(ref users, sectionOwnerName);
            return users;
        }

        public void RequestForVoBo(int[] documentsId, Guid sourceList, string targetUser, string request)
        {
            VoBoAction voboRequest = new VoBoAction(sourceList, documentsId, request, targetUser);
            voboRequest.Execute();
        }

        public Archivo GetArchivo(int id)
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                SolicitudVB selectedVoBo = getSolicitud(id, dc);
                Archivo selectedArchive = getArchive(int.Parse(selectedVoBo.IdDocumento.ToString()), PeopleHelper.GetUserById(selectedVoBo.DueñoDocumentoId.Value).LoginName.GetUserWithOutDomain(), dc);
                return selectedArchive;
            }
        }

        public void Approval(int id, string comment, bool result)
        {

            string libraryName = string.Empty;
            //SPFile currentFile = null;
            string targetUserName = string.Empty;

            //Updating document
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                SolicitudVB selectedVoBo = getSolicitud(id, dc);
                SPUser targetUser = PeopleHelper.GetUserById(selectedVoBo.DueñoDocumentoId.Value);
                libraryName = targetUser.LoginName.GetUserWithOutDomain();
                targetUserName = targetUser.Name;
                string curLibrary = SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain();
                int targetId = int.Parse(SPContext.Current.Web.Lists[curLibrary].GetItemById(id)[CustomSiteColumns.FIELD_VOBO_ID].ToString());
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        currentSite.AllowUnsafeUpdates = true;
                        using (SPWeb currentWeb = currentSite.OpenWeb())
                        {
                            currentWeb.AllowUnsafeUpdates = true;
                            SPListItem curSolicitud = currentWeb.Lists[libraryName].GetItemById(targetId);
                            curSolicitud[CustomSiteColumns.FIELD_ARCHIVE_RESPONSE] = comment;
                            curSolicitud[CustomSiteColumns.FIELD_ARCHIVE_APPROVAL] = result;
                            curSolicitud[CustomSiteColumns.FIELD_DOCUMENT_CATEGORY] = TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_CATEGORY, GlobalConstants.METADATA_TERM_CATEGORY_RESPONDED);
                            curSolicitud.Log(string.Empty, DateTime.Now, result ? Support.Enums.TraceableOperation.Aprobado : Support.Enums.TraceableOperation.Rechazado, SPContext.Current.Web.CurrentUser.Name, comment);
                            curSolicitud.Update();

                            //removing list item
                            //string currentUserLibrary = currentWeb.CurrentUser.LoginName.GetUserWithOutDomain();
                            SPList currentList = currentWeb.Lists[curLibrary];
                            SPListItem solicitud = currentList.GetItemById(id);
                            solicitud[CustomSiteColumns.FIELD_CURRENT_ACTION] = "MoveTo";
                            solicitud.Update();
                            solicitud.Delete();
                            currentList.Update();
                            currentWeb.AllowUnsafeUpdates = false;
                        }
                        currentSite.AllowUnsafeUpdates = false;
                    }
                });

                //dc.SubmitChanges();
            }



        }

        private static SolicitudVB getSolicitud(int id, DCDocumentCenterDataContext dc)
        {
            SolicitudVB selectedVoBo = (from archive in dc.GetList<SolicitudVB>(SPContext.Current.List.Title)
                                        where archive.Id == id
                                        select archive).FirstOrDefault();
            return selectedVoBo;
        }

        private static Archivo getArchive(int id, string libraryTarget, DCDocumentCenterDataContext dc)
        {
            Archivo selectedArchive = (from archivo in dc.GetList<Archivo>(libraryTarget)
                                       where archivo.Id == id
                                       select archivo).FirstOrDefault();
            return selectedArchive;
        }

        private Seccion GetUserSection(string section)
        {
            string caml = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", section);
            Seccion userSection = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, caml, new Nullable<uint>()).FirstOrDefault();
            if (userSection == default(Seccion)) { throw new Exception(string.Format("La sección {0} no se encuentra", section)); }
            return userSection;
        }

    }
}
